package cn.tanghom.support.websocket;

import org.apache.log4j.Logger;
import org.springframework.web.socket.*;

import cn.tanghom.conf.CommonKey;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class SystemWebSocketHandler implements WebSocketHandler {

    /**
     * 日志实例
     */
    private static Logger logger = Logger.getLogger(SystemWebSocketHandler.class);

    private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info(session.getId() + " connect to the websocket success......");
        users.add(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
    	Object msg = message.getPayload();
    	//add@byron
    	if(msg instanceof String){ 
    		List<String> list = (List<String>) session.getAttributes().get("messages");
    		if(list==null){
    			list = new LinkedList<String>();
    			session.getAttributes().put("messages",list);
    		}
    		list.add(msg.toString());
    	}
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }
        logger.info(session.getId() + " websocket connection closed......");
        users.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.info(session.getId() + " websocket connection closed......");
        users.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给某个用户发送消息
     *
     * @param receiver 接收人名称
     * @param message
     */
    public void sendMessageToUser(Long receiver, TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.getAttributes().get(CommonKey.WEBSOCKET_USER_SESSION).equals(receiver)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    /**
     * 返回websokectsession
     * @return
     */
    public ArrayList<WebSocketSession> session(){
        return users;
    }
    
    /**
     * 返回websokectsession
     * @return
     */
    public WebSocketSession session(Long receiver){
    	for (WebSocketSession user : users) {
            if (user.getAttributes().get(CommonKey.WEBSOCKET_USER_SESSION).equals(receiver)) {
               return user;
            }
        }
    	return null;
    }
    
    /**
     * 返回websokectsession
     * @return
     */
    public WebSocketSession session(String receiver){
    	for (WebSocketSession user : users) {
            if (user.getPrincipal().equals(receiver)) {
               return user;
            }
        }
    	return null;
    }
}